package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.PageDto;
import com.itheima.dto.PagesDto;
import com.itheima.entity.YddLink;
import com.itheima.service.LinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ydd_link")
@Slf4j
public class LinkController {

    @Autowired
    private LinkService linkService;

    /**
     * 链接详情
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R<YddLink> list(Integer id){
        YddLink link = linkService.getById(id);
        return R.success(link);
    }

    /**
     * 修改链接
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody YddLink yddLink){
        linkService.updateById(yddLink);
        return R.success("修改成功");
    }


    /**
     * 删除连接
     * @param id
     * @return
     */
    @GetMapping("/del")
    public R<String> delete(Integer id){
        linkService.removeById(id);
        return R.success("删除成功");
    }

    /**
     * 添加链接
     * @param yddLink
     * @return
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody YddLink yddLink){
        linkService.save(yddLink);
        return R.success("添加成功");
    }

    @GetMapping("/list")
    public R<PagesDto<YddLink>> list(String type, Integer page, Integer limit){
        Page<YddLink> pageInfo = new Page<>(page,limit);
        PagesDto<YddLink> pageDto = new PagesDto<>();

        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddLink::getType,type);
        linkService.page(pageInfo,queryWrapper);


        BeanUtils.copyProperties(pageInfo,pageDto,"records");

        List<YddLink> records = pageInfo.getRecords();

        //总数
        Long total = pageInfo.getTotal();
        pageDto.setCount(total.intValue());

//总页数
        Long pages = pageInfo.getPages();
        pageDto.setTotalPages(pages.intValue());

//当前页码
        Long current = pageInfo.getCurrent();
        pageDto.setCurrentPage(current.intValue());

//每页数量
        Long size = pageInfo.getSize();
        pageDto.setPageSize(size.intValue());
        pageDto.setData(records);

        return R.success(pageDto);
    }
}
